package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"gochat/common"
	"gochat/domain/request"
	"gochat/domain/response/result"
	"gochat/models"
	"gochat/service"
	"gochat/utils"
	"gorm.io/gorm"
	"strconv"
)

// UserRegister @Summary 用户注册
// @Description 注册一个新用户
// @Tags 用户模块
// @Accept json
// @Produce json
// @Param data body request.UserRegisterRequest true "用户注册参数"
// @Success 200 {object} result.Result
// @Failure 400 {object} result.Result
// @Router /user/register [post]
func UserRegister(c *gin.Context) {
	var reqUser request.UserRegisterRequest
	err := c.ShouldBindBodyWithJSON(&reqUser)
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	service.User.SaveUser(c, reqUser)
}

// UpdateUser @Summary 更新用户
// @Description 根据 ID 更新用户信息
// @Tags 用户模块
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Param data body request.UserRegisterRequest true "用户更新参数"
// @Success 200 {object} result.Result
// @Failure 400 {object} result.Result
// @Router /user/{id} [put]
func UpdateUser(context *gin.Context) {
	var reqUser request.UserRegisterRequest
	err := context.ShouldBindBodyWithJSON(&reqUser)
	if err != nil {
		result.Fail(context, 400, "参数错误")
		return
	}
	id, _ := strconv.Atoi(context.Param("id"))
	var user = models.UserBasic{
		Model:    gorm.Model{ID: uint(id)},
		UserName: reqUser.UserName,
		NickName: reqUser.NickName,
		Password: reqUser.Password,
		Email:    reqUser.Email,
		Phone:    reqUser.Phone,
	}
	service.User.UpdateUser(context, user)
}

// DeleteUser @Summary 删除用户
// @Description 根据 ID 删除用户
// @Tags 用户模块
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} result.Result
// @Failure 400 {object} result.Result
// @Router /user/{id} [delete]
func DeleteUser(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	var u = models.UserBasic{}
	if err := u.DeleteById(common.DB, id); err != nil {
		result.Fail(c, 500, "删除用户失败")
		return
	}
	result.Ok(c, "删除用户成功")
}

// OnlineNumber @Summary 查询在线人数
// @Description 查询当前在线用户数量
// @Tags 用户模块
// @Produce json
// @Success 200 {object} result.Result
// @Router /user/online [get]
func OnlineNumber(c *gin.Context) {
	key := "user:online:*"
	keys := common.RDB.Keys(context.Background(), key)
	rst, _ := keys.Result()
	result.Ok(c, len(rst))
}

func GetUserInfo(c *gin.Context) {
	uid, err := utils.GetUid(c)
	if err != nil {
		result.Fail(c, 400, "参数错误")
		return
	}
	service.User.GetUserInfoById(c, uid)
}
